<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { useRouterPush } from '@/hooks/common/router';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useCaptcha } from '@/hooks/business/captcha';
import { getServiceBaseURL } from '@/utils/service';
import { $t } from '@/locales';

defineOptions({
  name: 'ResetPwd'
});

const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useNaiveForm();
const { label, isCounting, loading, getCaptcha } = useCaptcha();
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);

// 添加登录类型枚举
enum LoginType {
  Phone = 'phone',
  Email = 'email'
}

interface FormModel {
  account: string;
  captcha: string;
  password: string;
  confirmPassword: string;
}

const model: FormModel = reactive({
  account: '',
  captcha: '',
  password: '',
  confirmPassword: ''
});

// 当前登录类型
const loginType = ref(LoginType.Phone);

// 图像验证码相关状态
const showCaptchaModal = ref(false);
const imageCaptchaValue = ref('');
const imageCaptchaData = reactive({ src: `${baseURL}/api/getCaptcha` });

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  const { formRules, createConfirmPwdRule } = useFormRules();

  return {
    account: loginType.value === LoginType.Phone ? formRules.phone : formRules.email,
    captcha: formRules.code,
    password: formRules.pwd,
    confirmPassword: createConfirmPwdRule(model.password)
  };
});

// 切换登录类型
function toggleLoginType() {
  loginType.value = loginType.value === LoginType.Phone ? LoginType.Email : LoginType.Phone;
  model.account = '';
  model.captcha = '';
}

// 刷新图像验证码
function refreshImageCaptcha() {
  const timestamp = new Date().getTime();
  imageCaptchaData.src = `${baseURL}/api/getCaptcha?t=${timestamp}`;
  imageCaptchaValue.value = '';
}

// 处理获取验证码按钮点击
function handleGetCaptcha() {
  // 先验证账号格式
  if (model.account.trim() === '') {
    window.$message?.error?.(
      loginType.value === LoginType.Phone ? $t('form.phone.required') : $t('form.email.required')
    );
    return;
  }

  // 根据类型验证格式
  const isPhone = loginType.value === LoginType.Phone;
  const isValid = isPhone ? /^1[3-9]\d{9}$/.test(model.account) : /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(model.account);

  if (!isValid) {
    window.$message?.error?.(isPhone ? $t('form.phone.invalid') : $t('form.email.invalid'));
    return;
  }

  // 显示图像验证码弹窗
  refreshImageCaptcha();
  showCaptchaModal.value = true;
}

// 验证图像验证码并获取短信验证码
async function verifyImageCaptcha() {
  if (!imageCaptchaValue.value.trim()) {
    window.$message?.error?.($t('form.code.required'));
    return;
  }

  // 这里可以添加图像验证码验证的API调用
  // 为了演示，假设验证通过
  try {
    // 模拟验证请求
    await new Promise(resolve => {
      setTimeout(resolve, 300);
    });

    // 隐藏弹窗
    showCaptchaModal.value = false;

    // 调用获取验证码的函数，传递账号和类型
    await getCaptcha(model.account, { type: loginType.value });
  } catch {
    window.$message?.error?.($t('form.code.invalid'));
    refreshImageCaptcha();
  }
}

async function handleSubmit() {
  await validate();
  // request to reset password with account and type
  window.$message?.success($t('page.login.common.validateSuccess'));
}
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <div class="account-input-wrapper">
      <div class="login-type-toggle">
        <div class="toggle-tab" :class="[{ active: loginType === LoginType.Phone }]" @click="toggleLoginType">
          {{ $t('page.login.common.phone') }}
        </div>
        <div class="toggle-tab" :class="[{ active: loginType === LoginType.Email }]" @click="toggleLoginType">
          {{ $t('page.login.common.email') }}
        </div>
      </div>
      <NFormItem path="account">
        <NInput
          v-model:value="model.account"
          :placeholder="
            loginType === LoginType.Phone
              ? $t('page.login.common.phonePlaceholder')
              : $t('page.login.common.emailPlaceholder')
          "
        />
      </NFormItem>
    </div>
    <NFormItem path="captcha">
      <div class="w-full flex-y-center gap-16px">
        <NInput v-model:value="model.captcha" :placeholder="$t('page.login.common.codePlaceholder')" />
        <NButton size="large" :disabled="isCounting" :loading="loading" @click="handleGetCaptcha">
          {{ label }}
        </NButton>
      </div>
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem path="confirmPassword">
      <NInput
        v-model:value="model.confirmPassword"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.confirmPasswordPlaceholder')"
      />
    </NFormItem>
    <NSpace vertical :size="18" class="w-full">
      <NButton type="primary" size="large" round block @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
      <NButton size="large" round block @click="toggleLoginModule('pwd-login')">
        {{ $t('page.login.common.back') }}
      </NButton>
    </NSpace>
  </NForm>

  <!-- 图像验证码弹窗 -->
  <NModal
    v-model:show="showCaptchaModal"
    :close-on-esc="true"
    preset="dialog"
    title="验证图片验证码"
    :close-on-click-overlay="false"
  >
    <div class="captcha-modal">
      <div class="captcha-image-container">
        <img :src="imageCaptchaData.src" alt="验证码" class="captcha-image" @click="refreshImageCaptcha" />
        <span class="captcha-hint">{{ $t('page.login.common.clickToRefresh') }}</span>
      </div>
      <div class="captcha-input-container">
        <NInput
          v-model:value="imageCaptchaValue"
          :placeholder="$t('page.login.common.enterCaptcha')"
          class="captcha-input"
          @keyup.enter="verifyImageCaptcha"
        />
      </div>
    </div>
    <template #footer>
      <NSpace>
        <NButton @click="showCaptchaModal = false">
          {{ $t('common.cancel') }}
        </NButton>
        <NButton type="primary" @click="verifyImageCaptcha">
          {{ $t('common.confirm') }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped>
.captcha-modal {
  text-align: center;
  padding: 16px 0;
}

.captcha-image-container {
  margin-bottom: 8px;
}

.captcha-hint {
  font-size: 12px;
  color: #999;
  display: block;
  margin-top: 8px;
}

.account-input-wrapper {
  margin-bottom: 24px;
}

.login-type-toggle {
  display: flex;
  border-radius: 8px;
  background-color: #f5f7fa;
  padding: 4px;
  margin-bottom: 16px;
  width: 100%;
  max-width: 320px;
  margin-left: auto;
  margin-right: auto;
}

.toggle-tab {
  flex: 1;
  text-align: center;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  color: #666;
  background-color: transparent;
}

.toggle-tab:hover {
  color: #1890ff;
}

.toggle-tab.active {
  background-color: #fff;
  color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  font-weight: 600;
}

.captcha-image {
  cursor: pointer;
  width: 200px;
  height: 60px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.captcha-input {
  margin-top: 16px;
}
</style>
